<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;
use User\Api\UserApi as UserApi;

/**
 * 用户控制器
 * 包括用户中心，用户登录及注册
 */
class UserController extends HomeController {

	/* 用户中心首页 */
	public function index(){
		//$login = A('User/User', 'Api')->login('麦当苗儿ss', 'aoiujz');
		//$login = A('User/User', 'Api')->register('麦当苗儿ss', 'aoiujz', 'xiaoxiaoxiao@qq.com');
		//$login = A('User/User', 'Api')->checkEmail('zuojiazi@vip.qq.com');


		// dump($login);
	
	}

	/* 注册页面 */
	public function register(){


		if(!IS_POST){ 
			$this->assign("generation",C("generation"));
			$this->assign("grade",C("grade"));
			$this->display();
			return false;
		}

		$mypost =I('post.');
		$msg=$this->checkData($mypost);

		if ($msg!=1) {
			die(array("status"=>"false","msg"=>$msg));
		}

		$Model_studen = D('studen');
 
		$count = $Model_studen->where(array('telephone'=>$mypost['telephone']))->count();
 
		if ($count>0) {
			die(json_encode(array("status"=>"false","msg"=>"电话已经被注册,不能继续注册")));
		}
 
		if (preg_match("/new2016/", $_SERVER['HTTP_REFERER'] )) {
		    $mypost['active_type'] = 4 ; //活动类型 = 4->扫码礼品
		}
 
		if (false==$Model_studen->add($mypost)) {
			
			die(json_encode(array("status"=>"false","msg"=>"未注册成功,请重试！")));
		} else {
			$newStuden_id=mysql_insert_id();
			$this->postAdminWorkCode($mypost['admin_work_code'],$newStuden_id);
			die(json_encode(array("status"=>"success")));
		}

	}
	//绑定到地推的工作号上
	private function postAdminWorkCode($adminWorkCode,$studen_id) {
		if (!$adminWorkCode)	 return false;

		$memberRow = getrow("select * From `ot_member` where work_code='{$adminWorkCode}' limit 1");

		$memberRow['studen_id'] = $studen_id;
 
		$this->saveAlloc($memberRow);
	}
	//绑定到地推的工作号上
	private function saveAlloc($row){
        //绑定处理
        $menber_bind_tag_Model = M('menber_bind_tag'); 

        $data = array();
        $data['studen_id'] = sprintf("%08d", $row['studen_id']);// 不足8位数，前置补零
        $data['member_uid'] = $row['uid']; 
        $data['u_type'] = $row['u_type']; 
        $data['create_time'] = time();
 
        $count = $menber_bind_tag_Model->where(array('studen_id'=>$row['studen_id'],'u_type'=>$row['u_type']))->count();
        
        if ($count ==0) {
            $menber_bind_tag_Model->add($data); // 根据条件保存修改的数据      
        }  

    }
    

	 private function checkData(&$param) {
        if (!$param['fullname']) {
            return "用户名必须输入";
        }
        $param['fullname']=safety_html($param['fullname']);
 
        if (false==$param['telephone'] && false!=$param['id']) {
            return "联系电话必须输入";
        }

        if (false!=$param['telephone']) {
            $tel=$param['telephone'];
            $isMob="/^1[3-5,8]{1}[0-9]{9}$/";
            $isTel="/^([0-9]{3,4}-)?[0-9]{7,8}$/";
            if(!preg_match($isMob,$tel) && !preg_match($isTel,$tel))
            {
                return '手机或电话号码格式不正确。如果是固定电话，必须形如(xxxx-xxxxxxxx)!';
            }
        }

        if (false==$param['grade']) {
        	return '年级不能为空!';
        }
 
        $param['registered_time'] = time();
        

        return 1;

    }

	/* 登录页面 */
	public function login($username = '', $password = '', $verify = ''){

		if(IS_POST){ //登录验证
			/* 检测验证码 */
			if(!check_verify($verify)){
				$this->error('验证码输入错误！');
			}

			/* 调用UC登录接口登录 */
			$user = new UserApi;
			$uid = $user->login($username, $password);
			if(0 < $uid){ //UC登录成功
				/* 登录用户 */
				$Member = D('Member');
				if($Member->login($uid)){ //登录用户
					//TODO:跳转到登录前页面
					$this->success('登录成功！',U('Home/Index/index'));
				} else {
					$this->error($Member->getError());
				}

			} else { //登录失败
				switch($uid) {
					case -1: $error = '用户不存在或被禁用！'; break; //系统级别禁用
					case -2: $error = '密码错误！'; break;
					default: $error = '未知错误！'; break; // 0-接口参数错误（调试阶段使用）
				}
				$this->error($error);
			}

		} else { //显示登录表单
			$this->display();
		}
	}

	/* 退出登录 */
	public function logout(){
		if(is_login()){
			D('Member')->logout();
			$this->success('退出成功！', U('User/login'));
		} else {
			$this->redirect('User/login');
		}
	}

	/* 验证码，用于登录和注册 */
	public function verify(){
 
		if (false==($telephone=$_POST['telephone'])) $msg[]="参数错误";
		if (false==($code=$_POST['code'])) $msg[]="参数错误";
 	 
		 
		if (isset($msg)) {
			die (json_encode(array("status"=>"error","msg"=>$msg[0])));
		}
		if ($_SESSION['vode']==  $code) {
			die (json_encode(array("status"=>"success")));
		} else {
			die (json_encode(array("status"=>"error","id"=>"vcode","msg"=>"验证码输入错误！")));
		}

		

	}

	/* 验证码，用于登录和注册 */
	public function verifyTelephone(){
		$Model_studen = D('studen');
 		$mypost =I('post.');
		$count = $Model_studen->where(array('telephone'=>$mypost['telephone']))->count();
 		
		if ($count>0) {
			die(json_encode(array("status"=>"error","id"=>"phone","msg"=>"电话已经被注册,不能继续注册")));
		} 
		die(json_encode(array("status"=>"success")));

	}

	/* 验证码，用于登录和注册 */
	public function crateaVerify(){

 		$mypost =I('post.');
 		if (false==$mypost['telephone']) {
 		 	die(json_encode(array("status"=>"error","msg"=>"参数错误")));
 		}
 		$Model_studen = D('studen');
		$count = $Model_studen->where(array('telephone'=>$mypost['telephone']))->count();
		if ($count>0) {
			die(json_encode(array("status"=>"error","id"=>"phone","msg"=>"电话已经被注册,不能继续注册")));
		}

 		$vode = rand(100000,999999);
 		//$vode = "123456";
		$_SESSION['vode']= $vode;
		die(json_encode(array("status"=>"success" )));
	}

	/**
	 * 获取用户注册错误信息
	 * @param  integer $code 错误编码
	 * @return string        错误信息
	 */
	private function showRegError($code = 0){
		switch ($code) {
			case -1:  $error = '用户名长度必须在16个字符以内！'; break;
			case -2:  $error = '用户名被禁止注册！'; break;
			case -3:  $error = '用户名被占用！'; break;
			case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
			case -5:  $error = '邮箱格式不正确！'; break;
			case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
			case -7:  $error = '邮箱被禁止注册！'; break;
			case -8:  $error = '邮箱被占用！'; break;
			case -9:  $error = '手机格式不正确！'; break;
			case -10: $error = '手机被禁止注册！'; break;
			case -11: $error = '手机号被占用！'; break;
			default:  $error = '未知错误';
		}
		return $error;
	}


    /**
     * 修改密码提交
     * @author huajie <banhuajie@163.com>
     */
    public function profile(){
        if ( IS_POST ) {
            //获取参数
            $uid        =   is_login();
            $password   =   I('post.old');
            $repassword = I('post.repassword');
            $data['password'] = I('post.password');
            empty($password) && $this->error('请输入原密码');
            empty($data['password']) && $this->error('请输入新密码');
            empty($repassword) && $this->error('请输入确认密码');

            if($data['password'] !== $repassword){
                $this->error('您输入的新密码与确认密码不一致');
            }

            $Api = new UserApi();
            $res = $Api->updateInfo($uid, $password, $data);
            if($res['status']){
                $this->success('修改密码成功！');
            }else{
                $this->error($res['info']);
            }
        }else{
            $this->display();
        }
    }

     /**
     * 发短信
     * @author huajie <banhuajie@163.com>
     */
    public function regsendsms(){
    	
    	// get_sendsms_url
    	$mypost =I('post.');
 		if (false==$mypost['telephone']) {
 		 	die(json_encode(array("status"=>"error","msg"=>"参数错误")));
 		} 
 		$message = "你的注册验证码是:".$_SESSION['vode'];

 		$url = get_sendsms_url($mypost['telephone'],$message);

 		error_log("\r\n\r\n".date("Y-m-d H:i:s")."短信发送{$mypost['telephone']}:".$url,3,DATA_PATH."sendsms_log".date("Y-m-d").".txt");
 		
 		$httpstr = curlhttp($url, $data, 'post', array("Content-type: text/html; charset=utf-8"));
 	
 		$httpstr = trim($httpstr);
 		error_log("\r\n".date("Y-m-d H:i:s")."短信发送{$mypost['telephone']}回复内容:".($httpstr),3,DATA_PATH."sendsms_log".date("Y-m-d").".txt");

 		//日志格式 电话;验证码;短信商返回值
 		$sms_replay = ($httpstr==1)?'ok':'false';
 		error_log("\r\n".date("Y-m-d H:i:s").";{$mypost['telephone']};{$_SESSION['vode']};{$sms_replay}",3,DATA_PATH."sendsms_all.txt");
    }

    public function regsuccess_sendsms(){

    	// get_sendsms_url
    	$mypost =I('post.');
	
 		if (false==$mypost['telephone']) {
 		 	die(json_encode(array("status"=>"error","msg"=>"参数错误")));
 		} 
 		$message = "恭喜您已成功领取威廉酷睿学科英语课程。我们会尽快联系您。欢迎您带领孩子来上课！";
 		if ($_REQUEST['active']=='new2016') {
			$res = D('studen')->where( array('telephone'=>$mypost['telephone']) )->find();
			$_id = floatval($res['id']);
 			//2016活动，注册成功后的提示。
 			$message = " 礼品申请成功。编号：".$_id;
 		}
 
 		$url = get_sendsms_url($mypost['telephone'],$message);

 		error_log("\r\n\r\n".date("Y-m-d H:i:s")."短信发送{$mypost['telephone']}:".$url,3,DATA_PATH."sendsms_log".date("Y-m-d").".txt");
 		
 		$httpstr = curlhttp($url, $data, 'post', array("Content-type: text/html; charset=utf-8"));
 		$httpstr = trim($httpstr);
 		error_log("\r\n".date("Y-m-d H:i:s")."短信发送{$mypost['telephone']}回复内容:".($httpstr),3,DATA_PATH."sendsms_log".date("Y-m-d").".txt");
    }
}
